package com.link.base.base.staticvalue.controller;

import com.alibaba.fastjson.JSON;
import com.link.base.base.appinfo.model.LoadFlag;
import com.link.base.base.appinfo.service.AppMobileInfoService;
import com.link.base.base.staticvalue.model.Staticvalue;
import com.link.base.base.staticvalue.service.StaticvalueService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.util.UserUtil;
import com.link.core.util.RedisUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 */
@Controller
@RequestMapping("/base/staticvalue")
public class StaticvalueController {
    @Resource
    private StaticvalueService service;

    @Resource
    private AppMobileInfoService appMobileInfoService;

    @RequestMapping(value = "/queryAll", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryAll(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("queryAll")
                .withMessage("获取值列表-start").flush();
        LinkRedisClient j = RedisUtil.getJedis();
        //使用corpId进行拼装,构建成不同的key
        //之类表key
        String redisKey = "app_lov_lov_all" + "_" + UserUtil.getUser().getCorpid();
        //值列表读取数据的可以
        String lovLoadDatakey = "lov_load_data" + "_" + UserUtil.getUser().getCorpid();
        try {
            List<Staticvalue> list;
            //获取当前corpid对应的之类表在数据库中更新时间的值
            LoadFlag temp = new LoadFlag();
            temp.setType("LOV");
            List<LoadFlag> loadFlagList = appMobileInfoService.getLoadDataFlag(temp);
            //获取当前corpid对应的之类表在缓存中更新时间的值
            String lovLoadDataValue = j.get(lovLoadDatakey);
            boolean lovUpdateFlag = false;
            LCLogger.info().withMessageKey("queryAll")
                    .withMessage("获取值列表-比较当缓存中上次更新时间和当前数据库中的更新时间").flush();
            //当缓存中上次更新时间和当前数据库中的更新时间相同时,标示没有更新过数据
            for (LoadFlag loadFlag : loadFlagList) {
                if (!loadFlag.getLastUpd().equals(lovLoadDataValue)) {
                    lovUpdateFlag = true;
                    j.set(lovLoadDatakey, loadFlag.getLastUpd());
                }
            }
            //值列表有更新,则直接查询数据库并更新缓存
            if (lovUpdateFlag) {
                LCLogger.info().withMessageKey("queryAll")
                        .withMessage("获取值列表-值列表有更新,则直接查询数据库并更新缓存").flush();
                list = service.queryAll(null);
                j.set(redisKey, JSON.toJSONString(list));
                //10分钟
                j.expire(redisKey, 60 * 10);
            } else {
                //否则判断是否有缓存,如果有缓存存在,则使用缓存,否则查询数据库
                LCLogger.info().withMessageKey("queryAll")
                        .withMessage("获取值列表-值列表无更新").flush();
                if (j.exists(redisKey)) {
                    list = JSON.parseArray(j.get(redisKey), Staticvalue.class);
                    LCLogger.info().withMessageKey("queryAll")
                            .withMessage("获取值列表-存在缓存,直接使用缓存中的数据").flush();
                } else {
                    list = service.queryAll(null);
                    j.set(redisKey, JSON.toJSONString(list));
                    //10分钟
                    j.expire(redisKey, 60 * 10);
                    LCLogger.info().withMessageKey("queryAll")
                            .withMessage("获取值列表-不存在缓存直接查询数据库,并将查询到的数据写入到缓存中").flush();
                }
            }
            LCLogger.info().withMessageKey("queryAll")
                    .withMessage("获取值列表-end").flush();
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
            LCLogger.error().withMessageKey("queryAll")
                    .withMessage("获取值列表-出现异常:" + e.getMessage()).flush();
        } finally {
            RedisUtil.returnResource(j);
        }

        return result;
    }


    @RequestMapping(value = "/queryLovGroupByTypes", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryLovGroupByTypes(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("queryLovGroupByTypes")
                .withMessage("获取值列表-start").flush();
        try {
            Staticvalue staticvalue = new Staticvalue();
            Map<String, List<Staticvalue>> lovs = service.queryLovGroupByTypes(staticvalue);
            result.put("success", true);
            result.put("result", lovs);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
            LCLogger.error().withMessageKey("queryLovGroupByTypes")
                    .withMessage("获取值列表-出现异常:" + e.getMessage()).flush();
        }

        return result;
    }

    /**
     * 根据传入的类型返回对象数组
     */
    @RequestMapping(value = "/queryByLovTypes", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryByLovTypes(Staticvalue record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Staticvalue> list = service.queryByLovTypes(record);
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }

    @RequestMapping(value = "/queryByLovType", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryByLovType(Staticvalue record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Staticvalue> list = service.queryByLovType(record);
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }

    @RequestMapping(value = "/queryByLovTypeMember")
    @ResponseBody
    public Map<String, Object> queryByLovTypeMember(@JsonParam Staticvalue record, HttpSession session, HttpServletRequest request,
                                                    HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Staticvalue> list = service.queryByLovType(record);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }

    /**
     * 分组查询值列表-不拦截
     * 查询逻辑与拦截版本相同,提供未登陆时使用
     * @author LiQun
     * @date 2018/12/19
     */
    @RequestMapping(value = "/queryLovGroupByTypesOuter", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryLovGroupByTypesOuter(@RequestBody Staticvalue staticvalue) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("queryLovGroupByTypes")
                .withMessage("获取值列表-start").flush();
        try {
            Map<String, List<Staticvalue>> lovs = service.queryLovGroupByTypes(staticvalue);
            result.put("success", true);
            result.put("result", lovs);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
            LCLogger.error().withMessageKey("queryLovGroupByTypes")
                    .withMessage("获取值列表-出现异常:" + e.getMessage()).flush();
        }

        return result;
    }

}
